﻿using Newtonsoft.Json;
using System.Configuration;
using System.IO;
using System.Net.Http;
using System.Text;

namespace Super.Hmi.Utils
{
    public class ChatAnywhereClient
    {
        private readonly string _apiKey = JsonHelper.AesDecrypt(ConfigurationManager.AppSettings["ChatGptApiKey"]); // 从配置文件中获取 API Key
        private readonly HttpClient _httpClient;
        private const string _model = "gpt-3.5-turbo"; // 使用 ChatAnywhere 的模型 
        private const string ApiEndpoint = "https://api.chatanywhere.com.cn/v1/chat/completions"; // ChatAnywhere API 端点
        public ChatAnywhereClient()
        {
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        }
        /// <summary>
        /// 获取 ChatAnywhere 的聊天响应
        /// </summary>
        /// <param name="prompt"></param>
        /// <returns></returns>
        public async Task<string> GetChatResponseAsync(string prompt)
        {
            var requestBody = new
            {
                model = _model,
                messages = new[]
                {
                new { role = "user", content = prompt }
            }
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync(ApiEndpoint, content);
            response.EnsureSuccessStatusCode();

            var responseJson = await response.Content.ReadAsStringAsync();
            dynamic responseData = JsonConvert.DeserializeObject(responseJson);

            return responseData.choices[0].message.content;
        }
        /// <summary>
        /// 流式获取 ChatAnywhere 的聊天响应
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="onCharacterReceived"></param>
        /// <returns></returns>
        public async Task StreamChatResponseAsync(string prompt, Action<string> onCharacterReceived)
        {
            var requestBody = new
            {
                model = _model,
                messages = new[]
                {
                    new { role = "user", content = prompt }
                },
                stream = true  // 关键参数，启用流式响应
            };
            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            using var response = await _httpClient.PostAsync(ApiEndpoint, content);
            response.EnsureSuccessStatusCode();
            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);
            StringBuilder fullResponse = new StringBuilder();
            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (!string.IsNullOrEmpty(line) && line.StartsWith("data:"))
                {
                    var jsonData = line.Substring(5).Trim();
                    if (jsonData == "[DONE]") break;
                    try
                    {
                        dynamic data = JsonConvert.DeserializeObject(jsonData);
                        string deltaContent = data?.choices[0]?.delta?.content?.ToString();

                        if (!string.IsNullOrEmpty(deltaContent))
                        {
                            fullResponse.Append(deltaContent);
                            foreach (char c in deltaContent)
                            {
                                onCharacterReceived(c.ToString());
                                await Task.Delay(50);  // 控制输出速度(毫秒)
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析错误: {ex.Message}");
                    }
                }
            }
            //onCharacterReceived($"\n[完整响应: {fullResponse}]");
        }
    }
}
